import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template, g
from flask.ext.sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from redis import StrictRedis
from flask_session import Session
from config import Config, config_dict

db = SQLAlchemy()
redis_store = None


def create_app(config_name):
    app = Flask(__name__)
    # 数据库对象
    config = config_dict.get(config_name)
    log_file(config.LEVEL)
    app.config.from_object(config)
    db.init_app(app)
    # redis对象
    global redis_store
    redis_store = StrictRedis(host=Config.Redis_Host, port=Config.Redis_Port, decode_responses=True)
    # 初始化Session对象
    Session(app)
    # 导入生成 csrf_token 值的函数
    from flask_wtf.csrf import generate_csrf

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    # CSRF保护
    CSRFProtect(app)
    # 注册蓝图
    from app.modules.index import index_blu
    app.register_blueprint(index_blu)
    from app.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from app.modules.news import news_blu
    app.register_blueprint(news_blu)
    from app.modules.user import user_blu
    app.register_blueprint(user_blu)
    from app.modules.admin import admin_blu
    app.register_blueprint(admin_blu)


    from app.utils.common import user_login_check
    @app.errorhandler(404)
    @user_login_check
    def notFound(e):
        return render_template('404.html',
                               data={
                                   "user_info": g.user.to_dict() if g.user else ""
                               })

    return app


# 日志文件集成
def log_file(level):
    logging.basicConfig(level=level)
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)
